package org.example.leetcode.core.service.impl.login;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.ibatis.ognl.Token;
import org.example.leetcode.common._enum.MailTypeEnum;
import org.example.leetcode.common._enum.YesOrNoEnum;
import org.example.leetcode.common.domain.SysUser;
import org.example.leetcode.common.exception.MyException;
import org.example.leetcode.common.utils.TokenUtils;
import org.example.leetcode.core.dao.SysUserMapper;
import org.example.leetcode.core.dto.SysUserTokenDto;
import org.example.leetcode.core.service.LoginService;
import org.example.leetcode.core.service.SysUserService;
import org.example.leetcode.core.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@Service
public class MailLogin implements LoginService {
    public static final boolean MAIL_SWITCH=true;
    private static final String MAIL_KEY= MailTypeEnum.Login.getName()+"::";
    private static final String REGISTER_MAIL_KEY= MailTypeEnum.Register.getName()+"::";
    private static final Integer VALID_TIME=60*60*24;
    @Resource
    RedisUtils redisUtils;
    @Resource
    SysUserService sysUserService;
    @Override
    @Transactional
    public SysUserTokenDto loginOrRegister(String phone, String password) {
        if(MAIL_SWITCH){
            String code = redisUtils.getValue(MailTypeEnum.Login.getName() + phone);
            if(!StringUtils.hasLength(code)){
                throw new MyException("验证码失效，请重新发送");
            }
            if(!code.equals(password)){
                throw new MyException("验证码不正确");
            }
        }
        SysUserTokenDto sysUserTokenDto = new SysUserTokenDto();
        //让验证码失效
        if(redisUtils.removeKey(MailTypeEnum.Register.getName()+phone)){
            //判断当前手机是否是第一次登录
            SysUser sysUser = sysUserService.getBaseMapper().selectOne(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getPhone, phone));
            String token;
            String refreshToken;
            //首次登录
            if(sysUser==null){
                SysUser newUser = new SysUser();
                newUser.setPhone(phone);
                newUser.setNickName("小卡拉米");
                sysUserService.getBaseMapper().insert(newUser);
                token=TokenUtils.createToken(newUser.getId(),phone);
                refreshToken=TokenUtils.createRefreshToken(newUser.getId(),phone);
                sysUserTokenDto.setIsNewUser(YesOrNoEnum.Yes.getCode());
                sysUserTokenDto.setNickName(newUser.getNickName());
            }
            else{
                token = TokenUtils.createToken(sysUser.getId(), phone);
                refreshToken=TokenUtils.createRefreshToken(sysUser.getId(),phone);
                sysUserTokenDto.setIsNewUser(YesOrNoEnum.No.getCode());
                sysUserTokenDto.setPic(sysUser.getPic());
                sysUserTokenDto.setNickName(sysUser.getNickName());
            }
            //保存refreshToken和accessToken
            redisUtils.setKey("ACCESS_TOKEN:"+phone,token,TokenUtils.TOKEN_VALID_TIME);
            redisUtils.setKey("REFRESH_TOKEN:"+phone,refreshToken,TokenUtils.TOKEN_VALID_TIME*7);
            sysUserTokenDto.setToken(token);
            return sysUserTokenDto;
        }
        return null;
    }

    public void send(String type,String phone) throws ExecutionException, InterruptedException {
        if(!phone.matches("\\d{11}")){
            throw new MyException("电话号码不规范");
        }
        String key = MailTypeEnum.getByCode(type);
        String value = redisUtils.getValue(key + phone);
        if(StringUtils.hasText(value)){
            throw new MyException("一分钟后重试");
        }
        String code = generateCode();
        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId("LTAI5tMgqzuauj7HHtePNyB8")
                .accessKeySecret("L3i5tw5AHEMSFf9hPUv3eCWVVHB5kD")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("zhc")
                .templateCode("SMS_465101171")
                .phoneNumbers(phone)
                .templateParam("{\"code\":\""+code+"\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();

        redisUtils.setKey(key+phone,code,VALID_TIME);
    }
    public static String generateCode()
    {
        Random r=new Random();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<4;i++)
        {
            sb.append(r.nextInt(10));
        }
        return sb.toString();
    }

}
